<template>
  <div class="app-container">
    <el-button v-if="checkPermission(permissionRoles.inner_grant_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
    <el-button v-if="checkPermission(permissionRoles.inner_grant_pass)" :disabled="disabled" type="success" icon="el-icon-s-check" class="filter-item" @click="pass()">批量审核</el-button>
    <el-button v-if="checkPermission(permissionRoles.inner_grant_del)" class="filter-item" type="danger" icon="el-icon-close" @click="handleDelete">批量删除</el-button>

    <el-table v-loading="listLoading" :data="list" class="mt-15" height="730" border :cell-class-name="cellClassNameFn" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="服务器" prop="sname" width="80px" align="center"></el-table-column>
      <el-table-column label="角色ID" prop="actor_id" width="110px" align="center"></el-table-column>
      <el-table-column label="角色名" prop="actor_name" width="90px" align="center"></el-table-column>
      <el-table-column label="代币类型" width="90px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.recharge_mode === 1">限时秘券</span>
          <span v-else>秘券</span>
        </template>
      </el-table-column>
      <el-table-column label="数量/ID" prop="used_num" width="120px" align="center"></el-table-column>
      <el-table-column label="使用人" prop="used_user" width="80px" align="center"></el-table-column>
      <el-table-column label="添加时间" prop="create_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="操作人" prop="create_user" width="80px" align="center"></el-table-column>
      <el-table-column label="审核时间" prop="review_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="审核人" prop="reviewer" width="80px" align="center"></el-table-column>
      <el-table-column align="center" label="操作" width="90px">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.inner_grant_pass) && row.status === 0" type="text" size="small" title="审核" @click="pass(row)">审核</el-button>
          <el-button v-if="checkPermission(permissionRoles.inner_grant_del) && row.status === 0" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="添加" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="角色ID">
          <el-input v-model="actorid" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" placeholder="角色ID,使用人（用英文逗号隔开）" @blur="handleBlueActorId" />
        </el-form-item>
        <el-table v-loading="listLoading" :data="actorList" border>
          <el-table-column label="区服" prop="sname" align="center"></el-table-column>
          <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
          <el-table-column label="角色名" prop="name" align="center"></el-table-column>
          <el-table-column label="等级" prop="level" align="center"></el-table-column>
          <el-table-column label="VIP" prop="vip" align="center"></el-table-column>
          <el-table-column label="剩余钻石" prop="diamond" align="center"></el-table-column>
          <el-table-column label="充值金额" prop="recharge" align="center"></el-table-column>
          <el-table-column label="剩余内币" prop="inner" align="center"></el-table-column>
          <el-table-column label="最后登录时间" prop="last_login_date" align="center"></el-table-column>
          <el-table-column label="上次发放时间" prop="last_date" align="center"></el-table-column>
          <el-table-column label="上次发放数量" prop="last_num" align="center"></el-table-column>
          <el-table-column label="使用人" prop="used_user" align="center"></el-table-column>
        </el-table>

        <el-form-item label="代币类型" prop="recharge_mode">
          <el-select v-model="dataForm.recharge_mode" class="defaut-input">
            <el-option label="限时秘券" value="1" />
            <el-option label="秘券" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="modelInner" label="代币数量" prop="used_num">
          <el-input v-model="dataForm.used_num" class="defaut-input" placeholder="请输入代币数量" />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getServerList } from '@/api/ops'
import { getActorInfo, getGrantList, handleGrant, deleteGrant, approvedGrant } from '@/api/operator'
import Pagination from '@/components/Pagination'

const defaultItem = {
  id: '',
  recharge_mode: '1',
  used_num: '',
  app_type: '',
  actor: []
}
export default {
  name: 'Grant',
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      permissionRoles: this.$store.state.user.permissionRoles,
      header: {
        Authorization: this.$store.state.user.token
      },
      dataForm: Object.assign({}, defaultItem),
      rules: {
        recharge_mode: [{ required: true, message: '请选择代币类型', trigger: 'blur' }],
        item: [{ required: true, message: '请选择充值选项', trigger: 'blur' }]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      servers: [],
      multipleSelection: [],
      total: 0,
      list: [],
      fileList: [],
      actorList: [],
      modelInner: true,
      disabled: false,
      actorid: '',
      dialogVisible: false
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      getGrantList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    async getServerList() {
      const res = await getServerList()
      this.servers = res.data.items
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleBlueActorId() {
      if (this.actorid === '' || this.actorid === undefined) return false
      getActorInfo({ actor_id: this.actorid }).then(response => {
        if (response.status) {
          this.actorList = response.data
        }
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.actor = this.actorList
          handleGrant(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    async handleDelete(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条记录')
        return false
      }

      this.$confirm('你确定要删除吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async() => {
        let d = []
        if (row) {
          d.push(row)
        } else {
          d = this.multipleSelection
        }
        deleteGrant(d).then(response => {
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        console.error(err)
      })
    },
    // 审核
    async pass(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条未审核的记录')
        return false
      }
      this.$confirm('你确定审核吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.disabled = true
        let d = []
        if (row) {
          d.push(row)
        } else {
          d = this.multipleSelection
        }
        approvedGrant(d).then(response => {
          this.disabled = false
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        console.error(err)
      })
    },
    cellClassNameFn(row) {
      if (row.columnIndex === 0 && row.row.status === 1) {
        return 'table-column-hidden'
      }
    },
    handleSelectionChange(items) {
      // 使用 filter 方法筛选出 status 为 0 的项
      this.multipleSelection = items.filter(item => item.status === 0)
      console.log(this.multipleSelection)
    }
  }
}
</script>

<style>
.el-tabs__header {
  margin: 0px;
}
</style>
